<template>
	<view class="content qxlj_back4">
		<view class="navbar">
			<view v-for="(item, index) in navList" :key="index" class="nav-item"
				:class="{current: tabCurrentIndex === index}" @click="tabClick(index)">
				{{item.text}}
			</view>
		</view>
		<swiper :current="tabCurrentIndex" class="swiper-box" duration="300" @change="changeTab">
			<swiper-item class="tab-content" v-for="(tabItem,tabIndex) in navList" :key="tabIndex">
				<scroll-view class="list-scroll-content" scroll-y @scrolltolower="loadData('add')">
					<!-- 订单列表 -->
					<view v-for="(item,index) in tabItem.orderList" :key="index" class="order-item">
						<!-- 订单头部信息 -->
						<view v-for="(goodsItem, goodsIndex) in item.OrdersOnlineInfoViewList" :key="goodsIndex">
							<view class="itemTitle">
								<text v-if="item.BusinessModel"
									@click="item.BusinessModel ? navGoodsDetail(item) : null"
									style="font-weight: bold;">{{item.BusinessModel.ShopName || '暂无数据'}}</text>
								<text v-else style="font-weight: bold;">暂无数据</text>
								<text class="stateTip">{{goodsItem.Type | statusTitle}}</text>
							</view>
							<view class="goods-box-single"
								@click="navToDetail(item,'order-detail/order-detail',goodsIndex)">
								<image class="goods-img" :src="goodsItem.Img" mode="aspectFill"></image>
								<view class="right">
									<view class="p-title">
										<text class="clamp">{{goodsItem.ProductName}}</text>

									</view>
									<text class="attr-box">数量: {{goodsItem.Num}} </text>
									<text class="attr-box">价格: <text
											class="price">{{goodsItem.SalePrice | toFixd}}</text></text>
									<text class="attr-box"
										v-if="[11,16,].includes(item.Type)">使用时间：{{goodsItem.ProductSpecStr.replace('使用时间','')}}</text>
									<!--<text class="attr-box">{{goodsItem.AddTime.replace('T',' ')}}</text>-->
									<!-- 									<text class="attr-box"
										v-if="![11,16].includes(item.Type) && ![1,2].includes(item.ProductType)">核销码:{{goodsItem.ProductOrdersCouponInfoModel ? goodsItem.ProductOrdersCouponInfoModel.Code : '' }}</text> -->

								</view>
							</view>
							<!-- 已付款 操作 -->
							<view class="" v-if="item.Type !== 17">
								<view class="price-box" v-if="item.ProductType !== 2">共计<text
										class="num">{{goodsItem.Num}}</text>件商品 总计:<text
										class="price">{{goodsItem.SalePrice*goodsItem.Num}}</text></view>
								<view class="action-box b-t">
									<button class="action-btn" v-if="[15].includes(item.Type) && item.ProductType !== 2"
										@click.stop="showPopup(2,item,[goodsItem])">申请退款</button>
									<button class="action-btn goPay"
										v-if="[2,6].includes(item.Type) && item.ProductType !== 2"
										@click.stop="navToDetail(item,'evaluation/evaluation',goodsIndex)">评价</button>
									<button class="action-btn goPay"
										v-if="[1].includes(item.Type) && item.ProductType !== 2"
										@click.stop="receipt(item)">确认收货</button>
									<button class="action-btn " v-if="item.ProductType !== 2"
										@click.stop="navToDetail(item,'order-detail/order-detail',goodsIndex)">查看详情</button>
								</view>
							</view>
						</view>
						<!-- 未付款操作 -->
						<view class="" v-if="item.Type === 17 || item.ProductType === 2">
							<view class="price-box">共计<text class="num">{{item.NumTotal}}</text>件商品 总计:<text
									class="price">{{item.SalePriceTotal | toFixd}}</text></view>
							<view class="action-box b-t">
								<button class="action-btn" v-if="[17].includes(item.Type)"
									@click.stop="showPopup(1,item,item.OrdersOnlineInfoViewList)">取消订单</button>
								<button class="action-btn goPay" v-if="[17].includes(item.Type)"
									@click.stop="payOrder(item,item.OrdersOnlineInfoViewList)">去付款</button>
								<button class="action-btn goPay" v-if="[2,6].includes(item.Type)"
									@click.stop="navToDetail(item,'evaluation/evaluation',goodsIndex)">评价</button>
								<button class="action-btn" v-if="[18,15,2].includes(item.Type)"
									@click.stop="showPopup(2,item,item.OrdersOnlineInfoViewList)">申请退款</button>
								<button class="action-btn goPay" v-if="[1].includes(item.Type)"
									@click.stop="receipt(item)">确认收货</button>
								<button class="action-btn " v-if="![17].includes(item.Type)"
									@click.stop="navToDetail(item,'order-detail/order-detail')">查看详情</button>
							</view>
						</view>
					</view>
					<!-- 空白页 -->
					<empty v-if="tabItem.loaded === true && tabItem.orderList.length === 0"></empty>
					<!-- 上拉加载更多 -->
					<uni-load-more v-else :status="tabItem.loadingType"></uni-load-more>
				</scroll-view>
			</swiper-item>
		</swiper>
		<cancel-popup ref="refcancel" @ok="handleOk" :isShowOnClick="isShowOnClick"></cancel-popup>
	</view>
</template>

<script>
	import uniLoadMore from '@/components/uni-load-more/uni-load-more.vue';
	import {
		orderList,
		editOrderStatus,
		orderPay,
		changeOrderPayStatus,
		delOrder
	} from '@/api/api.js'
	import {
		getUserOrderList,
		cancelOrders,
		refundOrders,
		productOrdersPay,
		acceptOrders
	} from '@/api/mall.js'
	import empty from "@/components/empty";
	import cancelPopup from '../components/cancel-popup.vue'
	import {
		mapState,
		mapMutations
	} from 'vuex'
	import {
		orderStateExp
	} from '@/utils/base.js'
	export default {
		components: {
			uniLoadMore,
			empty,
			cancelPopup,
		},
		data() {
			return {
				tabCurrentIndex: 0,
				showLogisticsStatus: [2, 3, 6], // 显示物流信息状态
				navList: [{
						state: 0,
						text: '全部',
						loadingType: 'more',
						orderList: [],
						parma: {
							TypeArr: "1,3,4,6,7,8,9,10,11,12,15,18,20"
							// TypeArr: ""
						},
						page: 1,
						pageSize: 10
					},
					// {
					// 	state: 1,
					// 	text: '待付款',
					// 	loadingType: 'more',
					// 	orderList: [],
					// 	parma: {
					// 		TypeArr: "17"
					// 	},
					// 	page: 1,
					// 	pageSize: 10
					// },
					{
						state: 2,
						text: '待使用',
						loadingType: 'more',
						orderList: [],
						parma: {
							TypeArr: '15,20',
							IsOnline: 1
						},
						page: 1,
						pageSize: 10,
					},
					{
						state: 3,
						text: '待收货',
						loadingType: 'more',
						orderList: [],
						parma: {
							TypeArr: '1,15,20',
							IsOnline: 0
						},
						page: 1,
						pageSize: 10
					},
					{
						state: 4,
						text: '退款/退货',
						loadingType: 'more',
						orderList: [],
						parma: {
							TypeArr: '3,4,7,8,9,10,11,12'
						},
						page: 1,
						pageSize: 10
					}
				],
				navType: 1,
				isShowOnClick: false,
			};
		},
		computed: {
			...mapState({
				userInfo: state => state.base.userInfo,
			}),
		},
		onUnload() {
			console.log('load')
			if (this.navType == 2) {
				uni.redirectTo({
					url: '/pages/center/index'
				})
			}
		},
		filters: {
			goodsImage(e) {
				let arr = JSON.parse(e) || []
				return arr[0]
			},
			toFixd(e) {
				let price = e * 1 || 0
				return price > 0 ? price.toFixed(2) : 0
			},
			statusTitle(e) {
				return orderStateExp(e).stateTip
			}
		},
		onLoad(options) {
			if (options.type != undefined) {
				this.navType = options.type;
			}

			uni.setNavigationBarTitle({
				title: '我的订单'
			});
			if (options.index != undefined) {
				this.tabCurrentIndex = options.index;
			}
			this.loadData('tabChange')
			//#ifdef H5
			this.$jwx.initJssdk()
			//#endif
		},
		methods: {
			...mapMutations(['setOrderDetail']),
			//获取订单列表
			async loadData(type = 'add') {
				//这里是将订单挂载到tab列表下
				let index = this.tabCurrentIndex;
				let navItem = this.navList[index];
				let parma = navItem.parma;
				if (type === 'tabChange' && navItem.loaded === true) {
					return;
				}

				if (type === 'refresh') {
					navItem.page = 1
				}

				if (type === 'add' || type === 'tabChange') {
					if (navItem.loadingType === 'nomore') {
						return;
					}
					navItem.loadingType = 'loading';
				} else {
					navItem.loadingType = 'more'
				}

				let {
					Data,
					Total
				} = await getUserOrderList({
					Index: navItem.page,
					Size: navItem.pageSize,
					...navItem.parma
				})
				console.log(3333, Data)
				if (type === 'tabChange' && !navItem.loaded) {
					this.$set(navItem, 'loaded', true)
				}

				let list = Data
				if (type === 'refresh') {
					navItem.orderList = [];
				}
				navItem.orderList = navItem.orderList.concat(list)
				//判断是否还有下一页，有是more并且页数加1  没有是nomore
				if (navItem.orderList.length < Total) {
					navItem.loadingType = 'more'
					navItem.page++
				} else {
					navItem.loadingType = 'nomore'
				}
			},
			//swiper 切换
			changeTab(e) {
				this.tabCurrentIndex = e.target.current;
				this.loadData('tabChange');
			},
			// 跳转商品详情
			navGoodsDetail(item) {
				console.log("item", item)
				const {
					Type,
					OrdersOnlineInfoViewList
				} = item;
				let Id = OrdersOnlineInfoViewList?.[0]?.ProductId
				let url = '/mall_subpages/goods-detail/goods-detail?id=${Id}&type=${Type}'
				// uni.navigateTo({
				// 	url
				// })
			},
			//跳转详情页
			navToDetail(item, page, index) {
				console.log('跳转详情页', item, page, index)
				let detail = this.$api.deepClone(item)
				console.log(detail)
				if (index !== undefined) {
					detail.OrdersOnlineInfoViewList = detail.OrdersOnlineInfoViewList.filter((t, i) => i === index)
				}
				this.setOrderDetail(detail)
				let url = `/mall_subpages/${page}?id=${detail.Id}&index=${index}`
				uni.navigateTo({
					url
				})
			},
			//顶部tab点击
			tabClick(index) {
				this.tabCurrentIndex = index;
			},
			//支付未支付订单	
			async payOrder(item, index) {
				const _this = this
				try {
					uni.showLoading({
						title: '提交中...',
						mask: true
					})

					const {
						Data
					} = await productOrdersPay({
						"OrdersOnLineId": item.OrdersOnLineId,
						"OrdersOnLineType": item.OrdersOnLineType,
						"Remark": ""
					})
					const params = JSON.parse(Data.WxJsApiParam)
					console.log('!!!', params)
					// uni.hideLoading()
					uni.requestPayment({
						provider: 'wxpay',
						timeStamp: params.timeStamp,
						nonceStr: params.nonceStr,
						package: params.package,
						signType: params.signType,
						paySign: params.paySign,
						success: function(res) {
							uni.hideLoading()
							_this.loadData('refresh')
							_this.clearData(_this.tabCurrentIndex)
						},
						fail: function(err) {
							uni.hideLoading()
							console.log('fail:' + JSON.stringify(err));
						}
					});
					// this.$jwx.wxpay({
					// 	timestamp: params.timeStamp, // 支付签名时间戳，注意微信jssdk中的所有使用timestamp字段均为小写。但最新版的支付后台生成签名使用的timeStamp字段名需大写其中的S字符
					// 	nonceStr: params.nonceStr, // 支付签名随机串，不长于 32 位  
					// 	package: params.package, // 统一支付接口返回的prepay_id参数值，提交格式如：prepay_id=\*\*\*）  
					// 	signType: params.signType, // 签名方式，默认为'SHA1'，使用新版支付需传入'MD5'  
					// 	paySign: params.paySign, // 支付签名 
					// },function(res){
					// 	_this.loadData('refresh')
					// 	_this.clearData(_this.tabCurrentIndex)
					// })

				} catch (e) {
					uni.hideLoading()
					uni.showToast({
						title: e.Msg,
						icon: 'none',
						duration: 2000
					})
					console.error('支付失败:', e)
					//TODO handle the exception
				}
			},
			//确认收货
			async receipt(item) {
				let _this = this
				const params = item.OrdersOnlineInfoViewList.map(row => {
					return {
						"InfoId": row.Id,
						"Remark": "",
						"ProductOrdersCouponInfoCode": row.Code,
						"LogisticsName": "",
						"LogisticsANO": "",
						"OrdersOnLineId": row.OrdersOnLineId,
						"OrdersOnLineType": row.OrdersOnLineType
					}
				})

				try {
					uni.showLoading({
						title: '请稍后'
					})
					const {
						Data
					} = await acceptOrders(params)
					this.$api.msg('收货成功')
					this.loadData('refresh')
					this.clearData(this.tabCurrentIndex)
					uni.hideLoading()
				} catch (e) {
					uni.hideLoading()
					uni.showToast({
						title: e.Msg,
						icon: 'none',
						duration: 2000
					})
					console.error('收货失败:', e)
					//TODO handle the exception
				}

			},

			//显示选择理由popup
			showPopup(type, item, goodsItem) {
				this.$refs.refcancel.show({
					type,
					item,
					goodsItem
				})
			},

			// 选择取消理由

			handleOk(e) {
				if (this.isShowOnClick) return;
				this.isShowOnClick = true;
				if (e.type === 1) {
					this.handleCancelOrder(e).finally(() => {
						this.isShowOnClick = false;
					});
				} else if (e.type === 2) {
					this.handleRefundOrder(e).finally(() => {
						this.isShowOnClick = false;
					});
				}
			},
			//申请退款
			async handleRefundOrder({
				item,
				goodsItem,
				title,
				LogisticsName,
				LogisticsANO
			}) {
				let _this = this
				// uni.showLoading({
				// 	title: '请稍后',
				// 	mask: true
				// })
				try {
					const params = goodsItem.map(row => {
						return {
							"InfoId": row.Id,
							"Remark": title,
							"LogisticsName": LogisticsName,
							"LogisticsANO": LogisticsANO,
							"ProductOrdersCouponInfoCode": row.Code,
							"OrdersOnLineId": item.OrdersOnLineId,
							"OrdersOnLineType": item.OrdersOnLineType,
						}
					})
					console.log('申请退款开始')
					await refundOrders(params);
					uni.hideLoading()
					_this.$refs.refcancel.hide()
					_this.$api.msg('申请成功')
					_this.loadData('refresh')
					_this.clearData(_this.tabCurrentIndex)
				} catch (e) {
					uni.hideLoading()
					uni.showToast({
						title: e.Msg,
						icon: 'none',
						duration: 2000
					})
					console.error('退款失败:', e)
					// TODO handle the exception
				}

			},
			//取消订单
			async handleCancelOrder({
				item,
				title
			}) {
				let _this = this
				console.log(444444, item, item.OrdersOnLineId, item.OrdersOnLineType, title);
				uni.showLoading({
					title: '请稍后'
				})
				try {
					const {
						Data
					} = await cancelOrders({
						"OrdersOnLineId": item.OrdersOnLineId,
						"OrdersOnLineType": item.OrdersOnLineType,
						"Remark": title
					});
					console.log(44444444444555, Data)
					_this.$api.msg('取消成功')
					_this.$refs.refcancel.hide()
					_this.loadData('refresh')
					_this.clearData(_this.tabCurrentIndex)
					uni.hideLoading()
				} catch (e) {
					uni.hideLoading()
					uni.showToast({
						title: e.Msg,
						icon: 'none',
						duration: 2000
					})
					console.error('取消失败:', e)
					//TODO handle the exception
				}
			},
			clearData(tIndex) {
				this.navList.forEach((item, index) => {
					if (tIndex !== index) {
						item.loadingType = 'more'
						item.page = 1
						item.loaded = false
						item.orderList = []
					}
				})
			},
			//完成评价
			handleCommentOrder(id) {},
			back() {
				uni.switchTab({
					url: '/pages/userCenter/center'
				})
			}
		},
	}
</script>

<style lang="scss">
	page,
	.content {
		background: #F0F4F3;
		height: 100%;
	}

	.swiper-box {
		height: calc(100% - 60px);
	}

	.list-scroll-content {
		height: 100%;
		padding: 4%;
		padding-top: 0;
		width: 92%;

	}

	.p-title {
		display: flex;
		justify-content: space-between;
		margin-top: 10rpx;

		.stateTip {
			color: #498FFF;
			font-size: $uni-font-size-base;
			font-weight: 600;
			line-height: 1;
			padding: 10rpx 0;
		}

		.clamp {
			// width: 350rpx;
			font-size: 15px;
			font-weight: 600;
			color: #111;
			line-height: 1;
			text-overflow: ellipsis;
			display: -webkit-box;
			-webkit-line-clamp: 2;
			overflow: hidden;
			-webkit-box-orient: vertical;
			margin-bottom: 20rpx;
			margin-top: 10rpx;
		}
	}

	.navbar {
		display: flex;
		height: 100rpx;
		padding: 0 5rpx;
		background: #FFF;
		//box-shadow: 0 1px 5px rgba(0,0,0,.06);
		position: relative;
		z-index: 10;

		.nav-item {
			flex: 1;
			display: flex;
			justify-content: center;
			align-items: center;
			height: 100%;
			font-size: 32rpx;
			color: #000;
			position: relative;

			&.current {
				// color: #111111;
				font-weight: bold;
				height: 100%;
				color: #498FFF;

				// &:after {
				// 	content: '';
				// 	position: absolute;
				// 	left: 50%;
				// 	bottom: 9px;
				// 	transform: translateX(-50%);
				// 	width: 50px;
				// 	height: 0;
				// 	border-bottom: 4rpx solid #498FFF;
				// }
			}
		}
	}

	.uni-swiper-item {
		height: auto;
	}

	.order-item {
		display: flex;
		flex-direction: column;
		/* padding-left: 30rpx; */
		width: 100%;
		/* margin-left: 3%; */
		background: #FFF;
		margin-top: 4%;
		border-radius: 10rpx;
		padding-left: 24rpx;

		.itemTitle {
			display: flex;
			align-items: center;
			justify-content: space-between;
			margin-top: 20rpx;

			.stateTip {
				color: #498FFF;
				font-size: $uni-font-size-base;
				font-weight: 600;
				line-height: 1;
				padding: 10rpx 0;
				margin-right: 5%;
			}
		}

		.i-top {
			display: flex;
			align-items: center;
			height: 80rpx;
			padding-right: 30rpx;
			font-size: $font-base;
			color: $font-color-dark;
			position: relative;

			.time {
				flex: 1;
			}

			.state {
				color: $base-color;
			}

			.del-btn {
				padding: 10rpx 0 10rpx 36rpx;
				font-size: $font-lg;
				color: $font-color-light;
				position: relative;

				&:after {
					content: '';
					width: 0;
					height: 30rpx;
					border-left: 1px solid $border-color-dark;
					position: absolute;
					left: 20rpx;
					top: 50%;
					transform: translateY(-50%);
				}
			}
		}

		.goods-box-single {
			display: flex;
			padding: 20rpx 0;

			.goods-img {
				display: block;
				width: 200rpx;
				height: 200rpx;
				background: #F8F8F8;
				border-radius: 14rpx;
			}

			.right {
				flex: 1;
				display: flex;
				flex-direction: column;
				padding: 0 30rpx 0 24rpx;
				overflow: hidden;

				.title {
					font-size: $uni-font-size-base + 2rpx;
					font-weight: 600;
					color: $font-color-dark;
					line-height: 1;
					@include overEllipsis;
					padding: 10rpx 0 20rpx 0;

				}

				.attr-box {
					font-size: $font-sm + 2rpx;
					color: $font-color-light;
					margin-bottom: 10rpx;
				}

				.price {
					font-size: $font-sm + 2rpx;
					color: #111;
					font-weight: bold;

					&:before {
						content: '￥';
						font-size: $font-sm;
						margin: 0 2rpx 0 8rpx;
					}
				}
			}
		}

		.price-box {
			display: flex;
			justify-content: flex-start;
			align-items: baseline;
			padding: 20rpx 30rpx 20rpx 220rpx;
			font-size: $font-sm + 2rpx;
			color: gray;
			@include overEllipsis;

			.num {
				margin: 0 8rpx;
				color: $font-color-dark;
			}

			.price {
				font-size: $font-sm + 2rpx;
				color: #111;
				font-weight: bold;
				font-size: 32rpx;

				&:before {
					content: '￥';
					margin: 0 2rpx 0 8rpx;
				}
			}
		}

		.action-box {
			display: flex;
			justify-content: flex-end;
			align-items: center;
			position: relative;
			padding-right: 30rpx;
		}

		.goPay {
			border: 2rpx solid #498FFF;
			color: #498FFF !important;
		}

		.action-btn {
			// width: 160rpx;
			height: 50rpx;
			padding: 20rpx !important;
			display: flex;
			align-items: center;
			margin: 0;
			padding: 0;
			text-align: center;
			line-height: 50rpx;
			margin: 20rpx 10rpx;
			font-size: $font-sm + 2rpx;
			color: $uni-text-color-grey;
			background: #f8f8f8;
			// border-radius: 100px;

			&:after {
				// border: 1px solid rgba($uni-text-color-grey,1);
				// border-radius: 100px;
			}

			&.recom {
				background: $uni-color-primary;
				color: #fff;

				&:after {
					border-color: $uni-color-primary;
				}
			}
		}
	}


	/* load-more */
	.uni-load-more {
		display: flex;
		flex-direction: row;
		height: 80rpx;
		align-items: center;
		justify-content: center
	}

	.uni-load-more__text {
		font-size: 24rpx;
		font-weight: normal;
		color: #CCCCCC;
	}

	.uni-load-more__img {
		height: 24px;
		width: 24px;
		margin-right: 10px
	}

	.uni-load-more__img>view {
		position: absolute
	}

	.uni-load-more__img>view view {
		width: 6px;
		height: 2px;
		border-top-left-radius: 1px;
		border-bottom-left-radius: 1px;
		background: #999;
		position: absolute;
		opacity: .2;
		transform-origin: 50%;
		animation: load 1.56s ease infinite
	}

	.uni-load-more__img>view view:nth-child(1) {
		transform: rotate(90deg);
		top: 2px;
		left: 9px
	}

	.uni-load-more__img>view view:nth-child(2) {
		transform: rotate(180deg);
		top: 11px;
		right: 0
	}

	.uni-load-more__img>view view:nth-child(3) {
		transform: rotate(270deg);
		bottom: 2px;
		left: 9px
	}

	.uni-load-more__img>view view:nth-child(4) {
		top: 11px;
		left: 0
	}

	.load1,
	.load2,
	.load3 {
		height: 24px;
		width: 24px
	}

	.load2 {
		transform: rotate(30deg)
	}

	.load3 {
		transform: rotate(60deg)
	}

	.load1 view:nth-child(1) {
		animation-delay: 0s
	}

	.load2 view:nth-child(1) {
		animation-delay: .13s
	}

	.load3 view:nth-child(1) {
		animation-delay: .26s
	}

	.load1 view:nth-child(2) {
		animation-delay: .39s
	}

	.load2 view:nth-child(2) {
		animation-delay: .52s
	}

	.load3 view:nth-child(2) {
		animation-delay: .65s
	}

	.load1 view:nth-child(3) {
		animation-delay: .78s
	}

	.load2 view:nth-child(3) {
		animation-delay: .91s
	}

	.load3 view:nth-child(3) {
		animation-delay: 1.04s
	}

	.load1 view:nth-child(4) {
		animation-delay: 1.17s
	}

	.load2 view:nth-child(4) {
		animation-delay: 1.3s
	}

	.load3 view:nth-child(4) {
		animation-delay: 1.43s
	}

	@-webkit-keyframes load {
		0% {
			opacity: 1
		}

		100% {
			opacity: .2
		}
	}
</style>